<template>
  <div class="page">
    <t-nav-bar
        title="报修申请"
        left-text="返回"
        left-arrow
        @click-left="handleBack"
    />
    <div class="content">
      <h1>报修申请</h1>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="auto" style="max-width: 600px" class="page">
        <el-form-item label="学  号" prop="userNo">
          <el-input v-model="form.userNo"/>
        </el-form-item>

        <el-form-item label="姓  名" prop="fullName">
          <el-input v-model="form.fullName"/>
        </el-form-item>

        <el-form-item label="标  题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>

        <el-form-item label="故障类型" prop="type">
          <el-select v-model="form.type" placeholder="故障类型">
            <el-option label="电气" value="电气" />
            <el-option label="管道" value="管道" />
            <el-option label="木工" value="木工" />
            <el-option label="其它" value="其它" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系电话" prop="contactNumber">
          <el-input v-model="form.contactNumber" />
        </el-form-item>

        <el-form-item label="维修地址" prop="repairAddress">
          <el-input v-model="form.repairAddress" />
        </el-form-item>

        <el-form-item label="故障描述" prop="faultDescription">
          <el-input
              v-model="form.faultDescription"
              type="textarea"
              :rows="5"
              placeholder="请详细描述故障情况"
              class="custom-textarea"
          />
        </el-form-item>

        <el-form-item class="button-container">
          <el-button type="primary" @click="onSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
        <el-form-item class="gotohistorybutton-container">
          <el-button @click="goToHistory">查看报修记录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, watchEffect} from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import {useStore} from "vuex";

const router = useRouter()
const formRef = ref(null)

const validatePhone = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入联系电话'))
  } else if (!/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的11位手机号码'))
  } else {
    callback()
  }
}

const rules = reactive({
  userNo: [
    { required: true, message: '请输入学号', trigger: 'blur' },
    { min: 4, max: 10, message: '学号长度应为10个字符之间', trigger: 'blur' }
  ],
  fullName: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度应在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择故障类型', trigger: 'change' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  repairAddress: [
    { required: true, message: '请输入维修地址', trigger: 'blur' },
    { min: 2, max: 100, message: '地址长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  faultDescription: [
    { required: true, message: '请输入故障描述', trigger: 'blur' },
    { min: 5, max: 500, message: '故障描述长度应在 5 到 500 个字符之间', trigger: 'blur' }
  ]
})

/*const store = useStore();
// 获取当前用户的信息
const user = store.getters.user;
// 检查用户是否已登录并且用户信息是完整的
if (!user || !user.userNo) {
  ElMessage.error('用户未登录或用户信息不完整');
} else {
  // 如果用户已登录且信息完整，则设置 form 中的 userNo 和 fullName
  form.userNo = user.userNo;
  form.fullName = user.fullName;
}

// 监听 store 中的用户信息变化
watchEffect(() => {
  const currentUser = store.getters.user;
  if (currentUser && currentUser.userNo) {
    form.userNo = currentUser.userNo;
    form.fullName = currentUser.fullName;
  }
});*/

const form = reactive({
  failureRepairId: null,
  userNo: '',
  fullName: '',
  type: '',
  title: '',
  repairTime: new Date().toISOString(),
  contactNumber: '',
  repairAddress: '',
  faultDescription: '',
  repairStatus: '申请中',
  createTime: new Date().toISOString(),
  updateTime: new Date().toISOString()
});

const handleBack = () => {
  router.back()
}

const onSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()

    // 提交报修申请
    const failureRepairPayload = {
      ...form,
      repairTime: new Date().toISOString(),
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };

    console.log('Submitting failure repair payload:', failureRepairPayload);
    const failureRepairResponse = await axios.post('http://localhost:8001/failure-repair/save', failureRepairPayload);

    if (failureRepairResponse.data) {
      ElMessage.success('报修申请提交成功！');

      // 从后端响应中获取 failureRepairId
      const failureRepairId = failureRepairResponse.data.failureRepairId;
      console.log('Submitting maintenance record payload:', failureRepairId);
      // 创建维修记录
      const maintenanceRecordPayload = {
        maintenanceRecordsId: null, // 使用从后端获得的 failureRepairId
        userNo: form.userNo,
        fullName: form.fullName,
        type: form.type,
        title: form.title,
        repairTime: new Date().toISOString(),
        contactNumber: form.contactNumber,
        repairAddress: form.repairAddress,
        faultDescription: form.faultDescription,
        employeeId: '',
        employeeName: '',
        dispatchTime: '',
        maintenanceStatus: '待处理',
        recordTime: ' ',
        repairDetails: '等待处理',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        evaStatus: '待评价',
        repairImage:"暂无图片"
      };

      console.log('Submitting maintenance record payload:', maintenanceRecordPayload);
      const maintenanceRecordResponse = await axios.post('http://localhost:8003/maintenance-records/save', maintenanceRecordPayload);

      if (maintenanceRecordResponse.data) {
        ElMessage.success('维修记录创建成功！');
        formRef.value.resetFields()
      } else {
        ElMessage.warning('报修申请提交成功，但维修记录创建失败。');
      }
    } else {
      ElMessage.error('报修申请提交失败，请重试。');
    }
  } catch (error) {
    if (error.errors) {
      console.error('Form validation failed:', error.errors)
      ElMessage.error('表单验证失败，请检查输入。')
    } else {
      console.error('Error submitting repair:', error)
      ElMessage.error('提交报修申请时发生错误，请重试。')
    }
  }
};

const goToHistory = () => {
  router.push('/fault-report')
}

const handleCancel = () => {
  ElMessageBox.confirm(
      '确定要取消此次报修吗?',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      } as any
  ).then(() => {
    router.push('/home')
  }).catch(() => {
    // 用户点击取消,不做任何操作
  })
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  font-family: Arial, sans-serif;
  background-color: white;
}

.content {
  flex: 1;
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.custom-textarea :deep(.el-textarea__inner) {
  min-height: 120px;
  line-height: 1.5;
  padding: 10px;
  font-size: 14px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-input,
.el-select {
  width: 100%;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}
.button-container {
  display: flex;
  justify-content: center;
  gap: 20px; /* 按钮之间的间距 */
}

.button-container :deep(.el-form-item__content) {
  margin-left: 0 !important; /* 覆盖 Element Plus 的默认样式 */
  justify-content: center;
}

.gotohistorybutton-container {
  display: flex;
  justify-content: center;
  margin-top: 20px; /* 可以根据需要调整上边距 */
}

.gotohistorybutton-container :deep(.el-form-item__content) {
  margin-left: 0 !important; /* 覆盖 Element Plus 的默认样式 */
  justify-content: center;
}

.gotohistorybutton-container .el-button {
  width: 80%; /* 可以根据需要调整按钮宽度 */
  max-width: 300px; /* 设置最大宽度，避免在大屏幕上过宽 */
}
</style>